package dblayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import modellayer.Invoice;

public class InvoiceDB implements IFInvoice {
	
	private Connection con;
	
	public InvoiceDB() {
		con = DBConnection.getInstance().getDBcon();
	}

	@Override
	public int insertInvoice(Invoice invoice) throws Exception {
		int rc = -1;
		
		
		// GHETTO KODE
		
		if (invoice==null) {
			invoice = new Invoice(0, "ghetto", 100.99);
		}
		
		
		String query = "INSERT INTO Invoice (paymentDate, amount) VALUES ('"+invoice.getPaymentDate()+"', '"+invoice.getAmount()+"');";
		
		try {
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			rc = stmt.executeUpdate(query);
			ResultSet rs = stmt.executeQuery("SELECT @@IDENTITY");
			rs.next();
			rc = rs.getInt(1);
			stmt.close();
		} catch(Exception ex) {
			System.out.println("SQL query: "+query);
			System.out.println("	error: "+ex);
			
			throw new Exception("Failed to insert Invoice to Database!");
		}
		
		return rc;
	}

	@Override
	public Invoice findInvoice(int invoiceId) {
		return singleWhere(" invoiceNo="+invoiceId+";");
	}

	
	private Invoice singleWhere(String wClause) {
		ResultSet results;
		Invoice invoice = null;
		
		String query = buildQuery(wClause);
		
		try {
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			
			if (results.next()) {
				invoice = buildInvoice(results);
			} else {
				invoice = null;
			}
			
			stmt.close();
		} catch (Exception ex) {
			System.out.println("SQL query: "+query);
			System.out.println("	error: "+ex);
		}
		
		return invoice;
	}
	
	private String buildQuery(String wClause) {
		String query = "SELECT invoiceNo, paymentDate, amount FROM Invoice";
		
		if (!wClause.isEmpty()) {
			query += " WHERE " + wClause;
		}
		
		return query;
	}
	
	private Invoice buildInvoice(ResultSet result) {
		Invoice invoice = null;
		try {
			invoice = new Invoice(result.getInt("invoiceNo"), result.getString("paymentDate"), result.getDouble("amount"));
		} catch (SQLException e) {
			System.out.println("Error building Laaner object!\nError: " + e);
		}
		
		return invoice;
	}
}
